package com.alibaba.algo.core.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by IntelliJ IDEA. User: glorysongglory Date: 2020/10/28 Time: 14:41
 */
@Slf4j
public class ProjectInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

		if (handler instanceof ResourceHttpRequestHandler) {
			return true;
		}
		if (handler instanceof HandlerMethod) {
			StringBuilder sb = new StringBuilder(1000);
			// 获取请求参数
			Enumeration em = request.getParameterNames();
			JSONObject data = new JSONObject();
			while (em.hasMoreElements()) {
				String name = (String) em.nextElement();
				String value = request.getParameter(name);
				data.put(name, value);
			}
			sb.append("\n-------------------------------------------------------------\n");
			HandlerMethod h = (HandlerMethod) handler;
			sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
			sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
			sb.append("Params    : ").append(data).append("\n");
			sb.append("URI       : ").append(request.getRequestURI()).append("\n");
			sb.append("URL       : ").append(request.getRequestURL()).append("\n");
			sb.append("-------------------------------------------------------------\n");
			log.info(sb.toString());
		}
		return true;
	}
}
